package org.ocean.general.sample.repository.impl;

import org.ocean.general.sample.conditional.Conditional;
import org.ocean.general.sample.helper.OptionalProviderHelper;
import org.ocean.general.sample.mapper.BaseMapper;
import org.ocean.general.sample.page.PageInfo;
import org.ocean.general.sample.repository.ServiceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

public class ServiceRepositoryImpl<M extends BaseMapper<T>, T> implements ServiceRepository<T> {

    @Autowired
    public BaseMapper<T> baseMapper;

    public ServiceRepositoryImpl(){

    }

    @Override
    public List<T> selectList() {
        return this.baseMapper.selectList();
    }

    @Override
    public List<T> selectByIds(String ids) {
        return this.baseMapper.selectByIds(ids.split(","));
    }

    @Override
    public T selectByPrimaryKey(Object key) {
        return (T) this.baseMapper.selectByPrimaryKey(key);
    }

    @Override
    public int selectByCount() {
        return this.baseMapper.selectByCount();
    }

    @Override
    public int selectByConditionalCount(Conditional conditional) {
        OptionalProviderHelper.buildConditionalParameter(conditional);
        return this.baseMapper.selectByConditionalCount(conditional);
    }

    @Override
    public List<T> selectByConditional(Conditional conditional) {
        OptionalProviderHelper.buildConditionalParameter(conditional);
        return this.baseMapper.selectByConditional(conditional);
    }

    @Override
    public PageInfo<T> selectPageByConditional(PageInfo<T> pageInfo, Conditional conditional) {
        pageInfo.initPageInfo();
        OptionalProviderHelper.buildConditionalParameter(conditional);
        List<T> list = this.baseMapper.selectPageByConditional(pageInfo, conditional);
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public PageInfo<T> selectBetweenPageByPrimaryKey(PageInfo<T> pageInfo) {
        pageInfo.initBetweenPageInfo();
        List<T> list = this.baseMapper.selectBetweenPageByPrimaryKey(pageInfo);
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public PageInfo<T> selectPageBySpecify(PageInfo<T> pageInfo, Conditional conditional) {
        if(pageInfo.isCalcSwitch()){
            pageInfo.initPageInfo();
        }
        if(!StringUtils.hasLength(pageInfo.getSpecifyFiled()) || Objects.isNull(pageInfo.getStartOffset()) || Objects.isNull(pageInfo.getEndOffset())){
            return pageInfo;
        }
        OptionalProviderHelper.buildConditionalParameter(conditional);
        List<T> list = this.baseMapper.selectPageBySpecifyWhere(pageInfo, conditional);
        pageInfo.setList(list);
        return pageInfo;
    }
}
